<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" fullscreen center :visible.sync="visible">
    <el-form class="verify-form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-row>
        <el-col :span="8" v-if="dataForm.id != 0">
          <el-form-item label="单号" prop="billId" v-if="dataForm.id != 0">
            <el-input v-model="dataForm.billId" placeholder="单号" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款日期" prop="createTime">
            <el-input v-model="dataForm.createTime" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单人" prop="createUserName">
            <el-input v-model="dataForm.createUserName" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="单据类型" prop="type">
            <el-radio-group v-model="dataForm.type" @change="changeType" disabled>
              <el-radio label="1">采购付款</el-radio>
              <el-radio label="2">预付款</el-radio>
              <el-radio label="3">厂商减账</el-radio>
              <el-radio label="4">调账</el-radio>
              <el-radio label="5">其他付款</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款种类" prop="payType">
            <el-radio-group v-model="dataForm.payType" disabled>
              <el-radio :label="1">按制造商</el-radio>
              <el-radio :label="2" :disabled="dataForm.type != 5">按部门</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制造商" v-if="dataForm.payType == 1" disabled>
            <el-input v-model="dataForm.supplyName" readonly v-if="dataForm.payType == 1">
              <el-button slot="append" @click="checkSupplyList">选择</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="部门" v-if="dataForm.payType == 2" disabled>
            <el-input v-model="dataForm.deptName" readonly>
              <el-button slot="append" @click="openDeptDialog">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本次核销" prop="writeOffAmount">
            <el-input v-model="dataForm.writeOffAmount" placeholder="本次核销" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本次付款" prop="payAmount">
            <el-input v-model="dataForm.payAmount" placeholder="本次付款" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="摘要" prop="memo">
            <el-input type="textarea" v-model="dataForm.memo" placeholder="摘要" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs type="border-card" v-if="dataForm.type == 1">
        <el-divider content-position="left">单据信息</el-divider>
        <div class="avue-crud">
          <el-table :data="dataList" border @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries1">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="linkBillId" label="源单编号"></el-table-column>
            <el-table-column prop="settlementTime" label="单据日期"></el-table-column>
            <el-table-column prop="linkBillType" label="源单类型"></el-table-column>
            <el-table-column prop="allWriteOffAmount" label="单据金额(含税)"></el-table-column>
            <el-table-column prop="doneWriteOffAmount" label="已核销金额(含税)"></el-table-column>
            <el-table-column prop="notWriteOffAmount" label="未核销金额(含税)"></el-table-column>
            <el-table-column prop="writeOffAmount" label="本次核销金额(含税)"></el-table-column>
            <el-table-column prop="memo" label="备注"></el-table-column>
          </el-table>
        </div>
      </el-tabs>

      <el-tabs type="border-card" v-if="dataForm.type == 5">
        <el-divider content-position="left">单据信息</el-divider>
        <div class="avue-crud">
          <el-table :data="dataList" border @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries2">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="subjectName" label="科目名称"></el-table-column>
            <el-table-column prop="writeOffAmount" label="本次核销金额(含税)"></el-table-column>
            <el-table-column prop="memo" label="备注"></el-table-column>
          </el-table>
        </div>
      </el-tabs>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj
  } from '@/api/eims/payslip'
  import SupplySearch from "@/components/business/SearchSupply"
  import SearchDept from './SearchDept'
  import ReturnManage from './return-management'
  import {
    mapGetters
  } from "vuex";
  export default {
    data() {
      return {
        visible: false,
        supplySearchVisible: false,
        deptVisible: false,
        returnVisible: false,
        dataForm: {
          id: 0,
          billId: '',
          writeOffAmount: '',
          payAmount: '',
          supplyId: '',
          supplyName: '',
          status: '',
          deptId: '',
          type: '',
          payType: '',
          memo: '',
          auditUser: '',
          auditUserName: '',
          auditTime: '',
          createTime: '',
          updateTime: '',
          createUser: '',
          modifyUser: '',
          createUserName: '',
          orgId: '',
          tenantId: '',
          unitId: '',
          delFlag: '',
          detailList: []
        },
        dataList: [],
        dataRule: {
          supplyId: [{
            required: true,
            message: '制造商id不能为空',
            trigger: 'blur'
          }],
          supplyName: [{
            required: true,
            message: '制造商名称不能为空',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '单据类型不能为空',
            trigger: 'blur'
          }],
          payType: [{
            required: true,
            message: '付款种类不能为空',
            trigger: 'blur'
          }],
          writeOffAmount: [{
            required: true,
            message: '本次核销金额不能为空',
            trigger: 'blur'
          }],
          payAmount: [{
            required: true,
            message: '本次付款金额不能为空',
            trigger: 'blur'
          }],
        }
      }
    },
    components: {
      SupplySearch,
      SearchDept,
      ReturnManage
    },
    created() {
      this.timeFormate(new Date());
    },
    computed: {
      ...mapGetters(["userInfo"])
    },
    methods: {
      init(id) {
        this.dataForm.id = id
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          getObj(this.dataForm.id).then(response => {
            if(response.data.code == '0'){
              this.dataForm = response.data.data
              this.dataList = response.data.data.detailList
            }else{
              this.$message.error(response.data.msg)
            }
          })

        })
      },
      // 表单提交
      dataFormSubmit() {
        this.dataForm.detailList = this.dataList
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              putObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              })
            } else {
              this.dataForm.createTime = ''
              addObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              })
            }
          }
        })
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      //选择制造商
      checkSupplyList() {
        let data = {};
        this.supplySearchVisible = true;
        this.$nextTick(() => {
          this.$refs.supplySearch.init(data);
        });
      },
      // 选择制造商
      renewFormData(data) {
        this.dataForm.supplyId = data.id;
        this.dataForm.supplyName = data.name;
      },
      //  打开查询部门弹窗
      openDeptDialog() {
        this.deptVisible = true
        this.$nextTick(() => {
          this.$refs.deptDialog.init()
        })
      },
      //  获取选择部门数据
      getDeptData(data) {
        this.dataForm.deptName = data.name
        this.dataForm.deptId = data.id
      },
      //显示当前时间（年月日时分秒）
      timeFormate(timeStamp) {
        let year = new Date(timeStamp).getFullYear();
        let month =
          new Date(timeStamp).getMonth() + 1 < 10 ?
          "0" + (new Date(timeStamp).getMonth() + 1) :
          new Date(timeStamp).getMonth() + 1;
        let date =
          new Date(timeStamp).getDate() < 10 ?
          "0" + new Date(timeStamp).getDate() :
          new Date(timeStamp).getDate();
        let hh =
          new Date(timeStamp).getHours() < 10 ?
          "0" + new Date(timeStamp).getHours() :
          new Date(timeStamp).getHours();
        let mm =
          new Date(timeStamp).getMinutes() < 10 ?
          "0" + new Date(timeStamp).getMinutes() :
          new Date(timeStamp).getMinutes();
        let ss =
          new Date(timeStamp).getSeconds() < 10 ?
          "0" + new Date(timeStamp).getSeconds() :
          new Date(timeStamp).getSeconds();
        this.nowTime =
          "POUT" +
          year +
          "" +
          month +
          "" +
          date +
          "" +
          hh +
          "" +
          mm +
          "" +
          ss +
          this.dataForm.deptId;
        this.dataForm.createTime = year + "-" + month + "-" + date;
      },
      // 删除选中的商品
      delTableData() {
        this.selectionList.forEach((item, index) => {
          for (let i = 0; i < this.dataList.length; i++) {
            if (this.dataList[i] == item) {
              this.dataList.splice(i, 1)
              this.dataForm.detailList.splice(i, 1)
            }
          }
          this.selectionList = []
        })
      },
      //根据获取采购单
      getInfo() {
        if (!this.dataForm.supplyId) {
          this.$message.warning("请选择制造商")
          return
        }
        this.returnVisible = true,
          this.$nextTick(() => {
            this.$refs.returnDialog.init(this.dataForm)
          })
      },
      getReturnData(data) {
        var list = []
        data.forEach(item => {
          item = item;
          item.linkBillType = "采购单"
          item.writeOffAmount = item.notWriteOffAmount
          list.push(item)
        })
        this.dataList = list
      },
      //  合计
      getSummaries1(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        sums[3] = '合计： '
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == 7 || index == 4 || index == 5 || index == 6) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        this.$set(this.dataForm, 'writeOffAmount', sums[7])
        this.$set(this.dataForm, 'payAmount', sums[7])
        return sums;
      },
      //  合计
      getSummaries2(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        sums[0] = '合计： '
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == 7 || index == 4 || index == 5 || index == 6) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      },
      changeType() {
        this.dataList = []
        this.dataForm.payType = 1
      }
    }
  }
</script>

<style lang="scss" scoped>
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
    order: 1;
  }
</style>
